import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { storage } from '@/utils'

export const useAppStore = defineStore('app', () => {
  // 状态
  const loading = ref(false)
  const loadingText = ref('加载中...')
  const sidebarCollapsed = ref(false)
  const device = ref('desktop') // desktop, tablet, mobile
  const language = ref(storage.get('language') || 'zh-CN')
  const breadcrumbs = ref([])
  const pageTitle = ref('')
  const notifications = ref([])
  const globalSettings = ref({
    showWatermark: false,
    enableAnimation: true,
    enableSound: true,
    autoSave: true,
    pageSize: 20
  })

  // 计算属性
  const isMobile = computed(() => device.value === 'mobile')
  const isTablet = computed(() => device.value === 'tablet')
  const isDesktop = computed(() => device.value === 'desktop')
  const hasNotifications = computed(() => notifications.value.length > 0)
  const unreadNotificationCount = computed(() => 
    notifications.value.filter(n => !n.read).length
  )

  // 设置加载状态
  const setLoading = (isLoading, text = '加载中...') => {
    loading.value = isLoading
    loadingText.value = text
  }

  // 显示加载
  const showLoading = (text = '加载中...') => {
    setLoading(true, text)
  }

  // 隐藏加载
  const hideLoading = () => {
    setLoading(false)
  }

  // 切换侧边栏
  const toggleSidebar = () => {
    sidebarCollapsed.value = !sidebarCollapsed.value
  }

  // 设置侧边栏状态
  const setSidebarCollapsed = (collapsed) => {
    sidebarCollapsed.value = collapsed
  }

  // 设置设备类型
  const setDevice = (deviceType) => {
    device.value = deviceType
    // 移动端自动收起侧边栏
    if (deviceType === 'mobile') {
      sidebarCollapsed.value = true
    }
  }

  // 设置语言
  const setLanguage = (lang) => {
    language.value = lang
    storage.set('language', lang)
  }

  // 设置面包屑
  const setBreadcrumbs = (crumbs) => {
    breadcrumbs.value = crumbs
  }

  // 添加面包屑
  const addBreadcrumb = (crumb) => {
    breadcrumbs.value.push(crumb)
  }

  // 清除面包屑
  const clearBreadcrumbs = () => {
    breadcrumbs.value = []
  }

  // 设置页面标题
  const setPageTitle = (title) => {
    pageTitle.value = title
    document.title = title ? `${title} - 苒兴教育` : '苒兴教育'
  }

  // 添加通知
  const addNotification = (notification) => {
    const id = Date.now().toString()
    const newNotification = {
      id,
      type: 'info', // info, success, warning, error
      title: '',
      message: '',
      duration: 4500,
      read: false,
      timestamp: new Date(),
      ...notification
    }
    
    notifications.value.unshift(newNotification)
    
    // 自动移除通知
    if (newNotification.duration > 0) {
      setTimeout(() => {
        removeNotification(id)
      }, newNotification.duration)
    }
    
    return id
  }

  // 移除通知
  const removeNotification = (id) => {
    const index = notifications.value.findIndex(n => n.id === id)
    if (index > -1) {
      notifications.value.splice(index, 1)
    }
  }

  // 标记通知为已读
  const markNotificationAsRead = (id) => {
    const notification = notifications.value.find(n => n.id === id)
    if (notification) {
      notification.read = true
    }
  }

  // 标记所有通知为已读
  const markAllNotificationsAsRead = () => {
    notifications.value.forEach(n => {
      n.read = true
    })
  }

  // 清除所有通知
  const clearAllNotifications = () => {
    notifications.value = []
  }

  // 清除已读通知
  const clearReadNotifications = () => {
    notifications.value = notifications.value.filter(n => !n.read)
  }

  // 显示成功消息
  const showSuccess = (message, title = '成功') => {
    return addNotification({
      type: 'success',
      title,
      message
    })
  }

  // 显示错误消息
  const showError = (message, title = '错误') => {
    return addNotification({
      type: 'error',
      title,
      message,
      duration: 6000
    })
  }

  // 显示警告消息
  const showWarning = (message, title = '警告') => {
    return addNotification({
      type: 'warning',
      title,
      message
    })
  }

  // 显示信息消息
  const showInfo = (message, title = '提示') => {
    return addNotification({
      type: 'info',
      title,
      message
    })
  }

  // 更新全局设置
  const updateGlobalSettings = (settings) => {
    globalSettings.value = { ...globalSettings.value, ...settings }
    storage.set('globalSettings', globalSettings.value)
  }

  // 重置全局设置
  const resetGlobalSettings = () => {
    globalSettings.value = {
      showWatermark: false,
      enableAnimation: true,
      enableSound: true,
      autoSave: true,
      pageSize: 20
    }
    storage.remove('globalSettings')
  }

  // 初始化应用
  const initApp = () => {
    // 从本地存储恢复设置
    const savedSettings = storage.get('globalSettings')
    if (savedSettings) {
      globalSettings.value = { ...globalSettings.value, ...savedSettings }
    }
    
    // 检测设备类型
    const checkDevice = () => {
      const width = window.innerWidth
      if (width < 768) {
        setDevice('mobile')
      } else if (width < 1024) {
        setDevice('tablet')
      } else {
        setDevice('desktop')
      }
    }
    
    checkDevice()
    
    // 监听窗口大小变化
    window.addEventListener('resize', checkDevice)
  }

  // 重置应用状态
  const resetAppState = () => {
    loading.value = false
    loadingText.value = '加载中...'
    sidebarCollapsed.value = false
    breadcrumbs.value = []
    pageTitle.value = ''
    notifications.value = []
    resetGlobalSettings()
  }

  return {
    // 状态
    loading,
    loadingText,
    sidebarCollapsed,
    device,
    language,
    breadcrumbs,
    pageTitle,
    notifications,
    globalSettings,
    
    // 计算属性
    isMobile,
    isTablet,
    isDesktop,
    hasNotifications,
    unreadNotificationCount,
    
    // 方法
    setLoading,
    showLoading,
    hideLoading,
    toggleSidebar,
    setSidebarCollapsed,
    setDevice,
    setLanguage,
    setBreadcrumbs,
    addBreadcrumb,
    clearBreadcrumbs,
    setPageTitle,
    addNotification,
    removeNotification,
    markNotificationAsRead,
    markAllNotificationsAsRead,
    clearAllNotifications,
    clearReadNotifications,
    showSuccess,
    showError,
    showWarning,
    showInfo,
    updateGlobalSettings,
    resetGlobalSettings,
    initApp,
    resetAppState
  }
}, {
  persist: {
    key: 'app-store',
    storage: localStorage,
    paths: ['sidebarCollapsed', 'language', 'globalSettings']
  }
})